package com.baidu.controller;


import com.alibaba.dubbo.config.annotation.Reference;
import com.baidu.constant.MessageConstant;
import com.baidu.entity.PageResult;
import com.baidu.entity.QueryPageBean;
import com.baidu.entity.Result;
import com.baidu.pojo.CheckItem;
import com.baidu.service.CheckItemService;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.web.bind.annotation.*;

import java.util.List;


/**
 * 检查项管理：
 */
@RestController //=Response+Controller
@RequestMapping("/checkitem")
public class CheckItemController {

	@Reference
	private CheckItemService itemService;



	@PreAuthorize("hasAuthority('CHECKITEM_ADD')")
	@RequestMapping("/add")
	public Result add(@RequestBody CheckItem checkItem) {//传递过来的是json、对象
		//我们先要做的功能是添加一条检查项的数据。
		//1.接受表单对象参数，
		//2.向服务层传递。
		//3.服务层向mapper层传递insert。//这里最好用配置文件的方式来 写。
		try {
			itemService.add(checkItem);
		return 	new Result(true, MessageConstant.ADD_CHECKITEM_SUCCESS);

		} catch (Exception e) {
			return 	new Result(false, MessageConstant.ADD_CHECKITEM_FAIL);
		}


	}


	@RequestMapping("/pageQuery") //我们最终返回是一个pageResult对象，该对象有总记录，当前页的结果。
	public PageResult pageQuery(@RequestBody QueryPageBean queryPageBean){
		//System.out.println(queryPageBean.getCurrentPage()+"//"+queryPageBean.getPageSize()+"//"+queryPageBean.getQueryString());
		PageResult pageResult = itemService.pageQuery(queryPageBean);
		//System.out.println(pageResult.getRows()+"//"+pageResult.getTotal());
		return pageResult;

	}

	@PreAuthorize("hasAuthority('CHECKITEM_DELETE')")
	@DeleteMapping("delete/{id}")
	public Result deleteByid(@PathVariable("id") Integer id){

		try {
			itemService.deleteByid(id);
			return new Result(true,MessageConstant.DELETE_CHECKITEM_SUCCESS);
		} catch (Exception e) {
	return new Result(false,MessageConstant.DELETE_CHECKITEM_FAIL);
		}


	}

	@GetMapping("findById/{id}")
	public Result findById(@PathVariable("id") Integer id){
		System.out.println("回显id"+id);

		try {
		CheckItem checkItem=itemService.findById(id);
			return new Result(true,MessageConstant.QUERY_CHECKITEM_SUCCESS,checkItem);
		} catch (Exception e) {
			return new Result(false,MessageConstant.QUERY_CHECKITEM_FAIL);
		}


	}

	@PreAuthorize("hasAuthority('CHECKITEM_EDIT')")
	@PostMapping("/edit")
	public Result editCheckItem(@RequestBody CheckItem checkItem){

		try {
			itemService.editCheckItem(checkItem);
			return new Result(true, MessageConstant.EDIT_CHECKITEM_SUCCESS);
		} catch (Exception e) {
			return new Result(false,MessageConstant.EDIT_CHECKITEM_FAIL);
		}


	}

//	回显
	@GetMapping("/findAll")
	public Result findAll(){
		try {
		List<CheckItem> list= itemService.findAll();
			return new Result(true,MessageConstant.QUERY_CHECKITEM_SUCCESS,list);
		} catch (Exception e) {
			return new Result(false,MessageConstant.QUERY_CHECKITEM_FAIL);
		}
	}





}
